package br.com.pheat.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.com.pheat.beans.Alimento;
import br.com.pheat.beans.RefeicaoAlimento;
import br.com.pheat.dao.AlimentoDAO;

public class RefeicaoAlimentoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public RefeicaoAlimentoServlet() {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		List<RefeicaoAlimento> refeicaoAlimentos = (List<RefeicaoAlimento>) session.getAttribute("refeicaoAlimentos");
		String func = request.getParameter("func");
		if(func.equals("add"))
		{
			if(refeicaoAlimentos==null)
				refeicaoAlimentos = new ArrayList<RefeicaoAlimento>();
			RefeicaoAlimento refeicaoAlimento = new RefeicaoAlimento();
			Float porcao = Float.parseFloat(request.getParameter("porcao"));
			try {
				Alimento alimento = AlimentoDAO.getAlimento(Integer.parseInt(request.getParameter("codigoAlimento")));
				refeicaoAlimento.setCalorias(alimento.getCalorias()*porcao);
				refeicaoAlimento.setAlimento(alimento);
				refeicaoAlimento.setPorcao(porcao);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			refeicaoAlimentos.add(refeicaoAlimento);
		} else if(func.equals("remover"))
		{
			refeicaoAlimentos.remove(Integer.parseInt(request.getParameter("indice")));
		}
		session.setAttribute("refeicaoAlimentos", refeicaoAlimentos);
		RequestDispatcher view = request.getRequestDispatcher("alimentos.jsp");
		view.forward(request, response);
	}

}
